from docx import Document
import requests,json
import sys,os,datetime

def getDocxInfo(document_id):
    
    # 发起网络请求获取json数据
    url = "http://ai.tinyask.cn/api/lunwen/getAiWriteInfo?document_id=" + str(document_id)
    response = requests.get(url, headers={
        'token': 'SWGf414y9OFeBn2amzbMatxkPgU9d6Vx'
    })
    # 将json数据转换为python对象
    data = json.loads(response.text)
    return data


def replace_text_with_format(paragraph, old_text, new_text):
    for run in paragraph.runs:
        # 检查文本运行是否包含要替换的旧文本
        if old_text in run.text:
            # 分割文本运行，以便在替换时保留格式
            new_text = new_text.replace('\\n', '\n')
            run.text=run.text.replace(old_text,new_text)

        

def getDocxParagraph(paragraphs, keyword):
    keyword = keyword
    # print(keyword)
    for paragraph in paragraphs:
        for run in paragraph.runs:
            # 检查文本运行是否包含要替换的旧文本
            if keyword in run.text:
                return paragraph
    return None

def handlePraagraph(paragraph, content):
    if paragraph:
        paragraph_lunwen_text_arr = content.split('\n')
        for text in paragraph_lunwen_text_arr:
            if text != '':
                paragraph.insert_paragraph_before(text)
def createDocxFile(id):
    DS = os.path.sep
    # 打开模板文档
    # doc = Document("D:\data\www\openai_lunwen\\aifile\论文模板\上海交通大学医学院继续教育学院论文模板.docx")

    document_info = getDocxInfo(id)
    school = document_info['data'].get('school', None)
    document = document_info['data']
    if not school:
        return "未设置学校信息"
    if not school['lunwen_template']:
        return "学校未设置模板文件"

    file_path = os.path.abspath(__file__)
    dir_path = os.path.dirname(file_path)


    # 拼接模板文件路径, 替换\为当前系统的路径分隔符
    template_file_path = os.path.abspath(os.path.dirname(__file__)) + os.path.sep + school['lunwen_template'].replace('\\', os.path.sep)
    
    # 判断模板文件是否存在
    if not os.path.exists(template_file_path):
        return "模板文件不存在"

    doc = Document(template_file_path)
    # print(document_info)
    # 定义要替换的变量和对应的值
    variables = {
    }

    replace_arr = ['title', 'summary', 'keywords', 'en_summary', 'en_keywords', 'references', 'thanks', 'en_title', 'article','zhuanye','username','name']
    document_info_items = document_info['data']
    for key in replace_arr:
        # 字典判断key是否存在
        # print(key)
        if key in document_info_items:
            variables[key] = document_info_items[key]
        else:
            variables[key] = ' '
    # print(variables)
    variables['article'] = '  '
    variables['summary'] = '  '
    variables['thanks'] = '  '
    article_paragraph = getDocxParagraph(doc.paragraphs, 'article')
    # print(article_paragraph)
    summary_paragraph = getDocxParagraph(doc.paragraphs, 'summary')
    thanks_paragraph = getDocxParagraph(doc.paragraphs, 'thanks')
    # 遍历文档中的段落
    for paragraph in doc.paragraphs:
        # 遍历段落中的所有占位符
        for key, value in variables.items():
            if key in paragraph.text:
                # 替换占位符为对应的值
                # print(key)
                # print(value)
                replace_text_with_format(paragraph, key, value)
    summary = document_info['data']['summary']
    thanks = document_info['data']['thanks']
    handlePraagraph(summary_paragraph, summary)
    handlePraagraph(thanks_paragraph, thanks)
    if article_paragraph:
        # 根据论文段落创建标题
        for paragraph_lunwen in document_info['data']['paragraphs']:
            if paragraph_lunwen['level'] == 1:
                article_paragraph.insert_paragraph_before(paragraph_lunwen['title'], style='论文标题一')
            elif paragraph_lunwen['level'] == 2:
                article_paragraph.insert_paragraph_before(paragraph_lunwen['title'], style='论文标题二')
            if paragraph_lunwen['text']:
                # paragraph_lunwen['text']
                # 将paragraph_lunwen['text']中的\n分割为数组
                handlePraagraph(article_paragraph, paragraph_lunwen['text'])

    # 保存替换后的文档
    # 获取年月日
    now = datetime.datetime.now()
    now_str = now.strftime('%Y%m%d')    
    dir_path = dir_path + DS + 'public' + DS + 'ailunwen' + DS + now_str + DS

    # 判断目录是否存在，不存在则创建
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    save_name = str(document['document_id']) + '-' + document['title'] + '.docx'
    save_path = dir_path + save_name
    doc.save(save_path)
    return save_path
id = sys.argv[1]
result = createDocxFile(id)
print(result)